<template>
    <view class="p-box">
        <view v-for="(m, i) in memberList" :key="m.id" class="row">
            <view class="user">
                <NetImage v-if="m.avatar" class="avatar" :src="m.avatar" />
                <LocalImage v-else class="avatar" src="default-avatar.png" />
                <view class="wrap">
                    <view class="nickname">{{ m.nickname || '用户' }}</view>
                    <view>{{ m.phone }}</view>
                </view>
            </view>
            <view class="unbind" @tap="unbind(i)">解除</view>
        </view>
        <view class="m-t-60">
            <nut-button type="primary" block size="large" @tap="bindUser">+增加用户</nut-button>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { bindUserApi, unbindUserApi, membersApi } from '@/api/PrivateDevice';
    import { showLoading, showModal, showToast, useRouter } from '@/utils/framework';
    import { ref } from 'vue';
    import LocalImage from '@/components/LocalImage/index.vue'
    import NetImage from '@/components/NetImage/index.vue'

    const router = useRouter()
    const deviceId = Number(router.params.id)
    
    const memberList = ref<any[]>([])

    function bindUser(){
        showModal({
            title : '输入手机号码',
            editable : true,
            async success(res) {
                if(res.confirm) {
                    const r = await bindUserApi(deviceId, res.content)
                    if(r.success) {
                        queryMembers()
                        showToast('绑定成功')
                    }else {
                        showToast('绑定失败')
                    }
                }
                
            }
        })
    }

    function unbind(index:number){
        showModal({
            title : '确定解除该用户吗',
            async success(res) {
                if(res.confirm) {
                    showLoading()
                    const r = await unbindUserApi(deviceId, memberList.value[index].id)
                    if(r.success) {
                        memberList.value.splice(index, 1)
                        showToast('解除成功')
                    }else {
                        showToast('解除失败')
                    }
                }
                
            }
        })
    }

    function queryMembers(){
        membersApi(deviceId).then(res => {
            if(res.success) {
                memberList.value = res.data
            }
        })
    }
    
    queryMembers()
</script>

<style lang="scss" src="./index.scss"></style>